package net.airtheva.uniqueTask2;

import java.io.IOException;
import java.io.StringReader;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.net.Uri;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;

public class Translator {

	public static Editable Convert(UserActivity activity, String content) {

		try {

			SpannableStringBuilder ssb = new SpannableStringBuilder();

			AtUserSpan aus = null;
			int ausLength = 0;

			// Copy from
			// http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html.
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			// factory.setNamespaceAware(true);
			XmlPullParser xpp = factory.newPullParser();

			xpp.setInput(new StringReader(content));
			int eventType = xpp.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_DOCUMENT) {
					System.out.println("Start document");

				}
				if (eventType == XmlPullParser.START_TAG) {
					System.out.println("Start tag " + xpp.getName());

					if (xpp.getName().equals("at")) {
						//Log.v("Translator", xpp.getAttributeValue(null, "userId"));
						int userId = Integer.parseInt(xpp.getAttributeValue(null, "userId"));
						aus = new AtUserSpan(activity, userId);
						ausLength = 0;
					}

					if (xpp.getName().equals("img")) {
						String uri = xpp.getAttributeValue(null, "src");
						ImageSpan is = new ImageSpan(activity, Uri.parse(Utils.CacheEmbeddedImage(activity, uri)));
						ssb.append("[image]");
						ssb.setSpan(is, ssb.length() - 7, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					}

				}
				if (eventType == XmlPullParser.TEXT) {
					System.out.println("Text " + xpp.getText());

					if (aus != null) {
						ausLength += xpp.getText().length();
					}

					ssb.append(xpp.getText());

				}
				if (eventType == XmlPullParser.END_TAG) {
					System.out.println("End tag " + xpp.getName());

					if (xpp.getName().equals("at")) {
						ssb.setSpan(aus, ssb.length() - ausLength, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
						ausLength = 0;
						aus = null;
					}

				}
				eventType = xpp.next();
			}
			System.out.println("End document");

			return ssb;

		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return (Editable) new SpannableStringBuilder("");

	}

	public static String Convert(Editable content) {

		String result = Html.toHtml(content);
		result = result.replaceAll("<img([^>]+)>", "<img$1 />");
		return result;

	}

}
